package com.heiyu.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heiyu.api.request.CollectDelRequest;
import com.heiyu.api.request.CollectListRequest;
import com.heiyu.api.request.CollectPutRequest;
import com.heiyu.api.response.CollectListResponse;
import com.heiyu.api.response.CommonResponse;
import com.heiyu.api.response.model.CollectListModel;
import com.heiyu.api.response.model.TargetInfoModel;
import com.heiyu.constants.ResponseMsgEnum;
import com.heiyu.controller.ApiBaseController;
import com.heiyu.dao.*;
import com.heiyu.entity.*;
import com.heiyu.utils.MoneyUtils;
import com.heiyu.utils.RangeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by mountain on 18/6/11.
 */
@Api(description = "自选相关接口")
@RestController
@RequestMapping("api/v1/collect")
public class CollectController extends ApiBaseController{


    @Autowired
    private UserFollowMapper userFollowMapper;
    @Autowired
    private GlobalShowInfoMapper globalShowInfoMapper;
    @Autowired
    private ShowInfoMapper showInfoMapper;
    @Autowired
    private CoinBaseInfoMapper coinBaseInfoMapper;
    @Autowired
    private MarketBaseInfoMapper marketBaseInfoMapper;
    @Autowired
    private MarketCoinCoinMapper marketCoinCoinMapper;

    @ApiOperation(value="list",notes = "获取自选列表")
    @RequestMapping(value="list",method = RequestMethod.GET)
    public CollectListResponse list(@ModelAttribute CollectListRequest request){
        CollectListResponse response = new CollectListResponse();
        UserInfo userInfo = getUser();
        if(userInfo==null){
            response.error(ResponseMsgEnum.USER_NOT_LOGIN);
        }else{
            UserFollow follow = new UserFollow();
            follow.setUserName(userInfo.getTelphone());
            List<UserFollow> list = this.userFollowMapper.selectList(follow);
            response.setData(new CollectListModel());
            response.getData().setList(new ArrayList<TargetInfoModel>());
            if(!CollectionUtils.isEmpty(list)){
                TargetInfoModel targetInfo;
                for(UserFollow info:list){
                    targetInfo = new TargetInfoModel();
                    targetInfo.setCollectId(info.getId());
                    formatDate(targetInfo,info);
                    if(targetInfo.getTargetId() != null)
                    response.getData().getList().add(targetInfo);
                }
            }
            response.success();
        }
        return response;
    }

    @ApiOperation(value="put",notes = "添加自选")
    @RequestMapping(value = "put",method = RequestMethod.POST)
    public CommonResponse put(@RequestBody CollectPutRequest targetIds){
        CommonResponse response = new CommonResponse();
        UserInfo userInfo = getUser();
        if(userInfo == null){
            response.error(ResponseMsgEnum.USER_NOT_LOGIN);
            return response;
        }
        if(StringUtils.isEmpty(targetIds.getType())){
            targetIds.setType("1");
        }
        if(!StringUtils.isEmpty(targetIds.getTargetIds())){
            UserFollow userFollow;
            List<UserFollow> list;
            String[] idx = targetIds.getTargetIds().split(",");
            CoinBaseInfo coinBaseInfo;
            if(targetIds.getType().equals("1")){
                for(String id:idx){
                    coinBaseInfo = new CoinBaseInfo();
                    coinBaseInfo.setTargetId(id);
                    coinBaseInfo = this.coinBaseInfoMapper.selectList(coinBaseInfo).get(0);
                    userFollow = new UserFollow();
                    userFollow.setFCoin(coinBaseInfo.getTargetId());
                    userFollow.setUserName(userInfo.getTelphone());
                    userFollow.setType("1");
                    list = this.userFollowMapper.selectList(userFollow);
                    if(CollectionUtils.isEmpty(list)){
                        this.userFollowMapper.insert(userFollow);
                        response.getData().setData(userFollow.getId()+"");
                    }else{
                        response.error("已经收藏过该币种信息");
                        return response;
                    }
                }
            }else{
                userFollow = new UserFollow();
                userFollow.setType("2");
                userFollow.setFCoin(targetIds.getTargetIds());
                userFollow.setUserName(userInfo.getTelphone());
                list = this.userFollowMapper.selectList(userFollow);
                if(CollectionUtils.isEmpty(list)){
                    this.userFollowMapper.insert(userFollow);
                    response.getData().setData(userFollow.getId()+"");
                }else{
                    response.error("已经收藏过该币种信息");
                    return response;
                }
            }

        }
        response.success();
        return response;
    }

    @ApiOperation(value="del",notes = "删除自选")
    @RequestMapping(value = "del",method = RequestMethod.POST)
    public CommonResponse del(@RequestBody CollectDelRequest request)
    {
        CommonResponse response = new CommonResponse();
        UserInfo userInfo = getUser();
        if(userInfo == null){
            response.error(ResponseMsgEnum.USER_NOT_LOGIN);
            return response;
        }
        String[] idx = request.getCollectIds().split(",");
        List<Long> ids = new ArrayList<Long>();
        for(String id:idx){
            ids.add(Long.valueOf(id));
        }
        this.userFollowMapper.batchDelete(ids);
        response.success();
        return response;
    }


    private void formatDate(TargetInfoModel info,UserFollow follow){
        //判断是否单币
        if(follow.getType().equals("1")){
            GlobalShowInfo globalShowInfo  = new GlobalShowInfo();
            globalShowInfo.setTargetId(follow.getFCoin());
            List<GlobalShowInfo> list = this.globalShowInfoMapper.selectList(globalShowInfo);
            if(CollectionUtils.isEmpty(list)){
                return;
            }
            globalShowInfo = list.get(0);
            if(globalShowInfo!=null){
                info.setMarketName("全网");
                info.setName(globalShowInfo.getSymbol());
                if(defaultSymbol()){
                    info.setPrice(MoneyUtils.formatter(globalShowInfo.getPriceCny(),false));
                    info.setTradeAmount(MoneyUtils.formatter(globalShowInfo.getVol24hCny(),true));
                }else {
                    info.setPrice(MoneyUtils.formatter(globalShowInfo.getPriceUsd(),false));
                    info.setTradeAmount(MoneyUtils.formatter(globalShowInfo.getVol24hUsd(),true));
                }
                info.setTargetId(globalShowInfo.getTargetId());
                CoinBaseInfo baseInfo = coinBaseInfoUtils.get(globalShowInfo.getTargetId());
                if(baseInfo != null){
                    info.setLogoUrl(baseInfo.getLogo());
                }
                info.setCnName(StringUtils.isEmpty(globalShowInfo.getCnName())?globalShowInfo.getUsName():globalShowInfo.getCnName());
                info.setRange(RangeUtil.formatter(globalShowInfo.getPercentChange24h()));
                info.setFullName(globalShowInfo.getUsName());
                info.setExchangePrice(MoneyUtils.formatter(globalShowInfo.getPriceUsd(),false));
            }
        }else{
            ShowInfo showInfo = showInfoMapper.selectPrimary(Long.valueOf(follow.getFCoin()));
            if(showInfo != null){
                info.setMarketName(showInfo.getMarketName());
                if(defaultSymbol()){
                    info.setPrice(MoneyUtils.formatter(showInfo.getPriceCny(),false));
                    info.setTradeAmount(MoneyUtils.formatter(showInfo.getVol24hCny(),true));
                }else {
                    info.setPrice(MoneyUtils.formatter(showInfo.getPriceUsd(),false));
                    info.setTradeAmount(MoneyUtils.formatter(showInfo.getVol24hUsd(),true));
                }
                info.setHasPic(hasPic(showInfo.getSymbol(),showInfo.getTCoin(),showInfo.getMarketName()));
                info.setExchangePrice(MoneyUtils.formatter(showInfo.getPriceUsd(),false));
                info.setRange(RangeUtil.formatter(showInfo.getPercentChange24h()));
                info.setTargetId(showInfo.getId()+"");
                info.setName(showInfo.getUsName());
                info.setSymbol(showInfo.getSymbol());
                info.setExchangeName(showInfo.getTCoin());
                JSONObject obj = null;
                try{
                    obj  = JSON.parseObject(redisUtils.get("MARKET_INFO_"+showInfo.getMarketName()));
                }catch (Exception e){
                    e.printStackTrace();
                    MarketBaseInfo marketBaseInfo = new MarketBaseInfo();
                    marketBaseInfo.setMarketName(showInfo.getMarketName());
                    marketBaseInfo = this.marketBaseInfoMapper.selectList(marketBaseInfo).get(0);
                    redisUtils.set("MARKET_INFO_"+follow.getMarketName(), JSON.toJSONString(marketBaseInfo));
                    info.setLogoUrl(marketBaseInfo.getLogo());
                }
                if(obj != null)
                    info.setLogoUrl(obj.getString("logo"));
            }
        }
    }

    private String hasPic(String usName,String toCoin,String marketName){
        if(marketName.indexOf(".")>=0){
            marketName = marketName.replace(".","");
        }
        MarketCoinCoin cMarketCoinCoin = new MarketCoinCoin();
        cMarketCoinCoin.setFCoin(usName);
        cMarketCoinCoin.setTCoin(toCoin);
        cMarketCoinCoin.setMarketName(marketName);
        List<MarketCoinCoin> list = this.marketCoinCoinMapper.selectList(cMarketCoinCoin);
        if(CollectionUtils.isEmpty(list))
            return "N";
        if(list.get(0).getHasKline()!=null && list.get(0).getHasKline()==1){
            return "Y";
        }
        return "N";
    }
}
